package com.ipcount.service;

import com.ipcount.properties.IpProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaozhua
 * @date 2022/9/13 11:14
 */
public class IpCountService {
    //采用map进行存储
    private Map<String, Integer> ipCountMap = new HashMap<>();
    //当前的request对象的注入工作由使用当前的starter的工程提供自动装配
    @Autowired
    private HttpServletRequest http;
    String ip = http.getRemoteAddr();
    public void count() {
        System.out.println("----------------自定义配置类---------------");
        //获取当前操作的ip
//        String ip = http.getLocalAddr();

//        System.out.println(ip);

        //判断ip是否为空
        Integer count = ipCountMap.get(ip);
        if (count == null) {
            ipCountMap.put(ip, 1);
        } else {
            ipCountMap.put(ip, count + 1);
        }
        System.out.println(ip + ":" + count);
        //每次调用当前操作，则记录当前ip,统计次数
    }

    /**
     * 挂载自定义属性配置类
     */
    @Autowired
    private IpProperties ipProperties;

    /**
     * 开启定时任务功能之后定时打印
     */
//    @Scheduled(cron = "0/5 * * * * ?")
//    @Scheduled(cron = "0/${tools.ip.cycle:5} * * * * ?")
//    @Scheduled(cron = "0/#{5} * * * * ?")
    public void print() {
        if (ipProperties.getModel().equals(IpProperties.LogModel.DETAIL.getValue())) {
            System.out.println("       IP访问复杂监控");
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.println("+--------------------+--------");
                System.out.println("| " + key + " | " + value + "   |");
                System.out.println("+---------------+--------");
            }
        }else if (ipProperties.getModel().equals(IpProperties.LogModel.SIMPLE.getValue())){
            System.out.println("       IP访问简单监控");
            System.out.println("+-----ip-address-----+");
            for (String key : ipCountMap.keySet()) {
                System.out.println("+--------------------+--------");
                System.out.println("| " + key + " |");
                System.out.println("+---------------+--------");
            }
        }

        if (ipProperties.getCyccleReset()) {
            //清理数据
            ipCountMap.clear();
        }
//        System.out.println("|                    |       |");
//        System.out.println("|                    |       |");
//        System.out.println("|                    |       |");
//        System.out.println("+--------------------+--------");
    }

//    public static void main(String[] args) {
//        new IpCountService().count();
//    }
}

